<?php

class ImagePickerWidget extends CInputWidget {

    public $assets;
    public $config;
    public $id;
    public $name;
    public $src;

    public function init() {
        parent::run();
        $assetObj = Yii::app()->getAssetManager();
        $assetObj->newFileMode = 0644; //fix bug on Matbao hosting
        $assetObj->newDirMode = 0755; //fix bug on Matbao hosting

        $path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR;
        $this->assets = $assetObj->publish($path);
    }

    public function run() {
        //set $_SESSION
        $_SESSION['file_manager'] = $this->config;
        
        //register Css & Script
        $cs = Yii::app()->getClientScript();
        $cs->registerScript('file-picker-' . $this->id, "
$('#$this->id').click(function() {
    var dialogID = '#null';

    $(dialogID).unbind('assignLink');
    $(dialogID).bind('assignLink', function() {
        var link = $(dialogID).data('link');
        if (link !== undefined) {
            $('#$this->id').html('<img src=\"' + link + '\" alt=\"$this->name\" />');
            
            $('#$this->id').next('p').remove();
            $('#$this->id').after('<p><a class=\"delete\" href=\"javascript:void(0)\">Delete</a></p>');
        }
    });

    url = '$this->assets/elfinder.php'
    loadFrame(url, dialogID, 900, 550, '', 'frameLinks', 'File picker');
});", CClientScript::POS_END);
        
        if ( empty($this->src) ) {
            $content = CHtml::tag('p', array(
                'class' => 'imagePicker',
                'id' => $this->id,
            ), '<span>' . $this->name . '</span>');
        } else {
            $content = CHtml::tag('p', array(
                'class' => 'imagePicker',
                'id' => $this->id,
            ), CHtml::image($this->src, $this->name));
            
            $link = CHtml::link('Delete', 'javascript:void(0)', array('class' => 'delete'));
            $content .= CHtml::tag('p', array(), $link);
        }
        
        $htmlOpts = array(
            'class' => 'imagePickerWrapper',
        );
        echo CHtml::tag('div', $htmlOpts, $content);
    }
    
}